package cn.hahah.module.blog.app.service.Impl;

import cn.hahah.framework.common.pojo.CommonResult;
import cn.hahah.framework.common.util.object.BeanUtils;
import cn.hahah.module.blog.app.JwtUtils;
import cn.hahah.module.blog.app.service.BlogAuthService;
import cn.hahah.module.blog.controller.admin.usercode.vo.UserCodeSaveReqVO;
import cn.hahah.module.blog.controller.admin.userhistorylogin.vo.UserHistoryLoginSaveReqVO;
import cn.hahah.module.blog.controller.admin.users.vo.UsersPageReqVO;
import cn.hahah.module.blog.controller.admin.users.vo.UsersRespVO;
import cn.hahah.module.blog.controller.admin.users.vo.UsersSaveReqVO;
import cn.hahah.module.blog.dal.dataobject.users.UsersDO;
import cn.hahah.module.blog.dal.mysql.users.UsersMapper;
import cn.hahah.module.blog.service.usercode.UserCodeService;
import cn.hahah.module.blog.service.userhistorylogin.UserHistoryLoginService;
import cn.hahah.module.blog.service.users.UsersService;
import cn.hahah.module.system.api.mail.MailSendApi;
import cn.hahah.module.system.api.mail.dto.MailSendSingleToUserReqDTO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BlogAuthServiceImpl implements BlogAuthService {
    @Resource
    private UsersService usersService;
    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private MailSendApi mailSendApi;
    @Resource
    private UserHistoryLoginService userHistoryLoginService;
    @Resource
    private UserCodeService userCodeService;

    @Override
    public CommonResult<UsersRespVO> login(String username, String password){

        List<UsersDO> users = usersMapper.selectByUsername(username);
        if (users.isEmpty()) {
            return CommonResult.error(400,"不存在该用户");
        }

        UsersDO user = users.get(0);
        if (!password.equals(user.getPassword())) {
            return CommonResult.error(400,"用户名或密码错误");
        }


        UserHistoryLoginSaveReqVO vo = new UserHistoryLoginSaveReqVO();
        vo.setUserId(user.getId());
        userHistoryLoginService.createUserHistoryLogin(vo);


		String jwt = jwtUtils.generateToken(user.getUsername(), user.getId());
        user.setPassword(jwt);
        CommonResult<UsersRespVO> res = CommonResult.success(BeanUtils.toBean(user, UsersRespVO.class));
        res.setMsg("登录成功"+user.getNickname());
        return res;
    }

    @Override
    public CommonResult<UsersRespVO> register(UsersSaveReqVO usersSaveReqVO) {
        Long userId =  usersService.createUsers(usersSaveReqVO);
        UsersDO usersDO =  usersService.getUsers(userId);
        CommonResult<UsersRespVO> res = CommonResult.success(BeanUtils.toBean(usersDO, UsersRespVO.class));
        res.setMsg("注册成功"+userId);
        return res;
    }

    @Override
    public CommonResult<String> resetPassword(String username, String newPassword) {
        List<UsersDO> usersDOList = usersMapper.selectByUsername(username);
        if (1 != usersDOList.size()) {
            return CommonResult.error(400,"找不到用户");
        }

        UsersDO usersDO = usersDOList.get(0);
        String Email = usersDO.getEmail();
        String templateCode = "admin-sms-login"; // 邮件模版，记得在【邮箱管理】中配置噢

        String token = jwtUtils.generateToken(username, usersDO.getId());
        String link = jwtUtils.generateResetLink(newPassword, token);
        Map<String, Object> templateParams = new HashMap<>();
        templateParams.put("link", link);
        mailSendApi.sendSingleMailToAdmin(new MailSendSingleToUserReqDTO()
                        .setMail(Email)
                        .setTemplateCode(templateCode)
                        .setTemplateParams(templateParams));

        CommonResult<String> res = CommonResult.success("发送成功");
        res.setMsg("发送成功");

        //添加记录
        UserCodeSaveReqVO vo = new UserCodeSaveReqVO();
        vo.setUserId(usersDO.getId());
        vo.setCode(token);
        userCodeService.createUserCode(vo);


        return res;
    }


    @Override
    public CommonResult<String> validateEmail(String newPassword, String token) {
        if(!jwtUtils.validateToken(token)){
            return CommonResult.error(400, "令牌验证失败");
        }

        String username = jwtUtils.getUsernameFromToken(token);
        List<UsersDO> usersDOList = usersMapper.selectByUsername(username);
        if (1 != usersDOList.size()) {
            return CommonResult.error(400,"找不到用户");
        }

        UsersDO usersDO = usersDOList.get(0);
        usersMapper.updatePasswordById(usersDO.getId(), newPassword);
        CommonResult<String> res = CommonResult.success("密码修改成功");
        return res.setMsg("密码修改成功");
    }
}
